package com.sql.test.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.R;
import com.location.test.LocationService;
import com.sql.test.service.DataFormatService;
import com.sql.test.service.RemoteDatabaseService;
import com.worldwind.test.GeometryCreator;
import com.worldwind.test.PickObjectController;

import java.util.ArrayList;

import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.geom.Camera;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globe.BasicElevationCoverage;
import gov.nasa.worldwind.globe.Globe;
import gov.nasa.worldwind.layer.BackgroundLayer;
import gov.nasa.worldwind.layer.BlueMarbleLandsatLayer;
import gov.nasa.worldwind.layer.RenderableLayer;
import gov.nasa.worldwind.layer.TiandituCia_cLayer;
import gov.nasa.worldwind.layer.TiandituImg_cLayer;
import gov.nasa.worldwind.render.Renderable;
import gov.nasa.worldwind.shape.Label;
import gov.nasa.worldwind.shape.Path;
import gov.nasa.worldwind.shape.Placemark;
import gov.nasa.worldwind.shape.Polygon;

/**
 * Created by Lenovo on 2018/5/7.
 */
/**
 * 实现基于关键字keyword的兴趣点poi查询
 * 思路：
 * 1、添加关键字输入框，确定查询按钮
 * 2、查询到的要素显示
 * 3、添加必要的图层
 * 4、添加要素选中监听
 * 5、添加定位功能模块
 * **/
public class RemotePoiSqlActivity extends AppCompatActivity {

    public EditText keywordEditText = null;
    public Button btnSearch = null;
    public String keyword ="";
    private ArrayList<String> columns = new ArrayList<>();


    private RemoteDatabaseService databaseService = new RemoteDatabaseService();
    private DataFormatService dataFormatService = new DataFormatService();
    private GeometryCreator geometryCreator= new GeometryCreator();

    private LocationService locationService =null;
    private WorldWindow wwd = null;
    private RenderableLayer locationLayer = new RenderableLayer();
    private RenderableLayer poiLayer = new RenderableLayer();
    private RenderableLayer labelsLayer = new RenderableLayer();
    //远程查询的线程间通信
    final  int SELECT_POI = 0;
    Handler handler =new Handler(){
        public void handleMessage(Message msg) {

            //如果返现msg.what，则进行制定操作，如想进行其他操作，则在子线程里将SHOW_RESPONSE改变
            switch (msg.what) {
                case SELECT_POI:

                    //2、查询到要素数据后进行绘制显示
                    ArrayList<String[]> poiData = (ArrayList<String[]>)msg.obj;
                    String geomText ,geomType = null;
                    ArrayList<Position> positions = null;
                    ArrayList<Position[]> multiPositions = null;
                    //feature number
                    if(poiData.size()>0) {
                        int featureNum = poiData.size();
                        for (int i = 0; i < featureNum; i++) {
                            //convert geometry data  text  format to digit
                            geomText = poiData.get(i)[poiData.get(i).length - 1];
                            //由于数据插入问题，或其他原因，空间数据为null的异常处理
                            if (geomText == null) {
                                geomType = "NONE";
                            } else {
                                geomType = dataFormatService.getGeomType(geomText);
                            }
                            //get atttibute number which used to limit loop
                            int attributeNum = poiData.get(i).length - 1;
                            Placemark placemark = null;
                            Path polyline = null;
                            Polygon polygon = null;
                            //draw feature by selected feature data
                            switch (geomType) {
                                case "POINT":
                                    //由一个图形组成，图形由一个点构成，点包含xy坐标
                                    positions = dataFormatService.getPositions(geomText);
                                    placemark = geometryCreator.createPlacemark(positions.get(0), poiData.get(i)[0]);
                                    Label placemarklabel = geometryCreator.createLabel(positions.get(0), poiData.get(i)[0]);
                                    //add attributes to feature except geometry attribute
                                    attributeNum = poiData.get(i).length - 1;
                                    for (int j = 0; j < attributeNum; j++) {
                                        placemark.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                    }

                                    poiLayer.addRenderable(placemark);
                                    labelsLayer.addRenderable(placemarklabel);
                                    wwd.requestRedraw();
                                    break;
                                case "LINESTRING":
                                    //由一个图形组成，图形由多个点构成，每个点包含xy坐标
                                    positions = dataFormatService.getPositions(geomText);
                                    polyline = geometryCreator.createPolyline(positions);
                                    //add attributes to feature except geometry attribute
                                    attributeNum = poiData.get(i).length - 1;
                                    for (int j = 0; j < attributeNum; j++) {
                                        polyline.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                    }
                                    poiLayer.addRenderable(polyline);
                                    wwd.requestRedraw();
                                    break;
                                case "POLYGON":
                                    //由一个图形组成，图形由多个点构成，每个点包含xy坐标,POLYGON((,,)),格式与LINESTRING(,,)有所不同
                                    multiPositions = dataFormatService.getMultiPositions(geomText);
                                    positions = new ArrayList<>();
                                    int pointNum = multiPositions.get(0).length;
                                    for (int m = 0; m < pointNum; m++) {
                                        positions.add(multiPositions.get(0)[m]);
                                    }
                                    polygon = geometryCreator.createPolygon(positions);
                                    //add attributes to feature except geometry attribute
                                    attributeNum = poiData.get(i).length - 1;
                                    for (int j = 0; j < attributeNum; j++) {
                                        polygon.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                    }
                                    poiLayer.addRenderable(polygon);
                                    wwd.requestRedraw();
                                    break;
                                case "MULTIPOINT":
                                    //由多个图形组成，每个图形包含一个点，每个点包含xy坐标
                                    positions = dataFormatService.getPositions(geomText);
                                    int pointsNumber = positions.size();
                                    for (int k = 0; k < pointsNumber; k++) {
                                        placemark = geometryCreator.createPlacemark(positions.get(k), poiData.get(i)[0]);
                                        //add attributes to feature except geometry attribute
                                        attributeNum = poiData.get(i).length - 1;
                                        for (int j = 0; j < attributeNum; j++) {
                                            placemark.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                        }
                                        poiLayer.addRenderable(placemark);
                                    }
                                    wwd.requestRedraw();
                                    break;
                                case "MULTILINESTRING":
                                    //由多个图形组成，每个图形又由多个点构成，每个点包含xy坐标
                                    multiPositions = dataFormatService.getMultiPositions(geomText);

                                    for (int k = 0; k < multiPositions.size(); k++) {
                                        positions = new ArrayList<>();
                                        int pointNumber = multiPositions.get(k).length;
                                        for (int m = 0; m < pointNumber; m++) {
                                            positions.add(multiPositions.get(k)[m]);
                                        }
                                        polyline = geometryCreator.createPolyline(positions);
                                        //add attributes to feature except geometry attribute
                                        attributeNum = poiData.get(i).length - 1;
                                        for (int j = 0; j < attributeNum; j++) {
                                            polyline.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                        }
                                        poiLayer.addRenderable(polyline);
                                    }
                                    wwd.requestRedraw();
                                    break;
                                case "MULTIPOLYGON":
                                    //由多个图形组成，每个图形又由多个点构成，每个点包含xy坐标
                                    multiPositions = dataFormatService.getMultiPositions(geomText);
                                    for (int k = 0; k < multiPositions.size(); k++) {
                                        positions = new ArrayList<>();
                                        int pointNumber = multiPositions.get(k).length;
                                        for (int m = 0; m < pointNumber; m++) {
                                            positions.add(multiPositions.get(k)[m]);
                                        }
                                        polygon = geometryCreator.createPolygon(positions);
                                        //add attributes to feature except geometry attribute
                                        attributeNum = poiData.get(i).length - 1;
                                        for (int j = 0; j < attributeNum; j++) {
                                            polygon.putUserProperty(columns.get(j), poiData.get(i)[j]);
                                        }
                                        poiLayer.addRenderable(polygon);
                                    }
                                    wwd.requestRedraw();
                                    break;
                                case "NONE":
                                    Toast.makeText(getApplicationContext(), "空间数据为空，查询失败！", Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        }
                        //显示到查询的要素位置
                        if (positions.size() > 0) {
                            Globe globe = wwd.getGlobe();
                            Camera camera = new Camera();
                            camera.set(positions.get(0).latitude, positions.get(0).longitude, 2500, WorldWind.ABSOLUTE, 0, 0, 0.0 /*roll*/);
                            wwd.getNavigator().setAsCamera(globe, camera);
                            wwd.requestRedraw();
                        }
                    }

                    break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //1、添加界面要素
        setContentView(R.layout.poi_sql);
        keywordEditText = (EditText)findViewById(R.id.keywordEdit);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.globe);

        //2、查询
        //设置兴趣点属性字段名
        columns.add("name");
        columns.add("address");
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取关键字
                keyword = keywordEditText.getText().toString();
                //开辟线程读取远程数据库
               new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<String[]>  poiData = databaseService.selectDataByKeyWord(keyword);
                        Message message = new Message();
                        message.what = SELECT_POI;
                        message.obj = poiData;
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });
        //3、加载必要图层
        wwd = new WorldWindow(this);
        frameLayout.addView(wwd);
        wwd.getLayers().addLayer(new BackgroundLayer());
        wwd.getLayers().addLayer(new BlueMarbleLandsatLayer());
        wwd.getLayers().addLayer(new TiandituImg_cLayer());
        wwd.getLayers().addLayer(new TiandituCia_cLayer());
        //add location layer
        wwd.getLayers().addLayer(locationLayer);
        //add record route layer：添加兴趣点及注记图层
        wwd.getLayers().addLayer(poiLayer);
        wwd.getLayers().addLayer(labelsLayer);
        wwd.getGlobe().getElevationModel().addCoverage(new BasicElevationCoverage());
        //4、添加要素选中监听
        wwd.setWorldWindowController(new PickObjectController(this));
        //5、定位服务
        locationService= new LocationService(this,wwd,locationLayer);
        locationService.startLocation();
    }
}
